/**
 * 说明
 * 控件：比例尺，缩放平移，地图/混合
 * 配置：禁止底图可点，中心点，默认等级，启用滚轮放大缩小
 * 回调：拖动回调，缩放回调，加载完毕回调
 * 获取：获取可视区域，可视区域左下角，可视区域右上角，获取缩放等级
 * 设置：移动地图中心，设置地图等级，设置地图中心
 * 添加：添加控件，跳动的动画，多边形，添加元素
 * 移除：移除控件，移除元素，清除覆盖物
 * 移动端点击事件
 */
const lat = 41.811871;
const lng = 123.439115;

let coverStorage = []; // 存储覆盖物
let polygonStorage = []; // 存储多边形区域
let circleStorage = []; // 存储圆形
let heatmapOverlay; // 热力图
let prevCircle; // 右键圆形区域


// map.clearOverlays(); // 清除覆盖物

/*控件*/
// 左上角，比例尺
const scaleControl = new BMap.ScaleControl({ anchor: BMAP_ANCHOR_TOP_LEFT });
// 左上角，缩放平移
const navigationControl = new BMap.NavigationControl();
// 右上角，地图/混合
const mapTypeControl = new BMap.MapTypeControl({
  mapTypes: [BMAP_NORMAL_MAP, BMAP_HYBRID_MAP],
});
/*地图初始化*/
// 禁止底图可点/等级
const map = new BMap.Map("map", {
  // 禁止底图可点
  enableMapClick: false,
  minZoom: 13,
  maxZoom: 19,
});
// 中心点/默认等级
map.centerAndZoom(new BMap.Point(lng, lat), 17);
// 添加比例尺
map.addControl(scaleControl);
// 启用滚轮放大缩小
map.enableScrollWheelZoom();
// 拖动回调
map.addEventListener("moveend", () => {
  // this指向map
  console.log("moveend");
  const bs = map.getBounds(); // 获取可视区域
  console.log(bs.getSouthWest()); // 可视区域左下角
  console.log(bs.getNorthEast()); // 可视区域右上角
});
// 缩放回调
map.addEventListener("zoomend", () => {
  console.log("zoomend");
});

// 加载完毕回调
// 当地图所有图块完成加载时触发此事件
map.addEventListener("tilesloaded", function () {
  var LEVEL = map.getZoom(); // 获取缩放等级
  console.log(LEVEL);
});

/**
 * 搜索回车事件
 */
// 搜索
$(".value").on("change", function () {
  handle.searchMap($(this)[0].value);
});
// 搜索结果列表点击
$(".list").on("click", "li", function () {
  handle.listClick($(this).data());
});
/**
 * 封装方法
 * add() 添加控件
 * remove() 移除控件
 * distance() 测距
 * polygonFn() 返回多边形地图数据
 * addCover() 添加覆盖物
 * removeCover()
 * addPolygen() 添加多边形
 * removePolygen()
 * addHot() 添加热力图
 * removeHot()
 * searchMap() 搜索
 * listClick() 搜索列表点击
 * addCircle() 圆形区域-测试移动端点击事件
 */
const handle = {
  // 私有属性
  prevMarker: null,
  // 添加控件
  add() {
    map.addControl(navigationControl);
    map.addControl(mapTypeControl);
  },
  // 移除控件
  remove() {
    map.removeControl(navigationControl);
    map.removeControl(mapTypeControl);
  },
  // 开启鼠标测距
  distance() {
    new BMapLib.DistanceTool(map).open();
  },
  // 多边形区域
  polygonFn(points) {
    const pointArr = [];
    for (let [index, elem] of points.split(";").entries()) {
      const arr = elem.split(",");
      pointArr[index] = new BMap.Point(arr[0], arr[1]);
    }

    return new BMap.Polygon(pointArr, {
      strokeColor: "#1ec3c8",
      fillColor: "#1ec3c8",
      strokeWeight: 2,
      strokeOpacity: 0.3,
      fillOpacity: 0.3,
    });
  },
  // 显示小区覆盖物
  addCover() {
    const self = this;

    const xqList = dbxq.obj.xq;
    // 移动地图中心
    map.panTo(new BMap.Point(xqList[0].lng, xqList[0].lat));

    xqList.forEach((ele) => {
      coverPoint = new ComplexCustomOverlayView(
        map,
        ele,
        self.polygonFn(ele.points)
      );
      // 添加元素
      map.addOverlay(coverPoint);
      coverStorage.push(coverPoint);
    });

  },
  removeCover() {
    coverStorage.forEach((ele) => {
      // 移除元素
      map.removeOverlay(ele);
    });
    coverStorage = [];
  },
  // 显示小区区域
  addPolygen() {
    const self = this;

    const areaList = dbarea.obj.xqquyu;

    // 移动地图中心
    map.panTo(new BMap.Point(123.444648, 41.796081));
    areaList.forEach((ele) => {
      const areaPolygon = self.polygonFn(ele.points);
      polygonStorage.push(areaPolygon);
      map.addOverlay(areaPolygon);
    });

  },
  removePolygen() {
    polygonStorage.forEach((ele) => {
      map.removeOverlay(ele);
    });
    polygonStorage = [];
  },
  // 显示热力图
  addHot() {

    const hotList = dbhot.data;

    const zoom = map.getZoom();
    // 移动地图中心
    map.panTo(new BMap.Point(123.447420, 41.795660));
    heatmapOverlay = new BMapLib.HeatmapOverlay({ radius: 20 });
    map.addOverlay(heatmapOverlay);
    heatmapOverlay.setDataSet({ data: hotList, max: 100 });
    switch (zoom) {
      case 12:
        heatmapOverlay.setOptions({ radius: "20" });
        break;
      case 13:
        heatmapOverlay.setOptions({ radius: "40" });
        break;
      case 14:
        heatmapOverlay.setOptions({ radius: "60" });
        break;
      case 15:
        heatmapOverlay.setOptions({ radius: "80" });
        break;
      case 16:
        heatmapOverlay.setOptions({ radius: "120" });
        break;
      case 17:
        heatmapOverlay.setOptions({ radius: "140" });
        break;
      case 18:
        heatmapOverlay.setOptions({ radius: "180" });
        break;
      default:
        heatmapOverlay.setOptions({ radius: "180" });
        break;
    }
    // 显示热力图
    heatmapOverlay.show();

  },
  removeHot() {
    // 隐藏热力图
    heatmapOverlay.hide();
  },
  // 搜索
  searchMap(value) {
    let list = "";
    const self = this;
    const local = new BMap.LocalSearch(map, {
      onSearchComplete(results) {
        // 判断状态是否正确
        if (local.getStatus() === BMAP_STATUS_SUCCESS) {
          const array = [];
          for (let index = 0; index < results.getCurrentNumPois(); index++) {
            const item = results.getPoi(index);
            array[index] = {
              lng: item.point.lng,
              lat: item.point.lat,
              title: item.title,
              address: item.address,
            };
          }
          if (array.length > 0) {
            // 生成第一个点
            const listItem = array[0];
            map.setZoom(17);
            if (self.prevMarker) {
              map.removeOverlay(self.prevMarker);
            }
            map.panTo(new BMap.Point(listItem.lng, listItem.lat));
            self.prevMarker = new BMap.Marker(
              new BMap.Point(listItem.lng, listItem.lat)
            );
            map.addOverlay(self.prevMarker);
            self.prevMarker.setAnimation(BMAP_ANIMATION_BOUNCE); // 跳动的动画
            // 插入列表
            array.forEach(function (ele, index) {
              list += `<li data-lng=${ele.lng} data-lat=${ele.lat}>${ele.title}</li>`;
            });
            $(".list").append(list);
          }
        } else {
          $(".list").html("");
        }
      },
    });
    local.search(value);
  },
  // 搜索列表点击
  listClick(item) {
    {
      if (this.prevMarker) {
        map.removeOverlay(this.prevMarker);
      }
      map.panTo(new BMap.Point(item.lng, item.lat));
      this.prevMarker = new BMap.Marker(new BMap.Point(item.lng, item.lat));
      map.addOverlay(this.prevMarker);
      this.prevMarker.setAnimation(BMAP_ANIMATION_BOUNCE); // 跳动的动画
    }
  },
  // 右键画圆
  circle(point, radius) {
    var zoomset = 0;
    switch (radius) {
      case 500: zoomset = 17; break;
      case 1000: zoomset = 16; break;
      case 1500: zoomset = 15; break;
      case 2000: zoomset = 15; break;
    }
    // 设置地图等级
    map.setZoom(zoomset);
    // 设置地图中心
    map.setCenter(point);
    map.removeOverlay(prevCircle);
    prevCircle = new BMap.Circle(point, radius, { fillOpacity: 0.2, fillColor: "#4673cc", strokeWeight: 1, strokeOpacity: 0.3 });
    map.addOverlay(prevCircle);//根据当前范围画一个大圆圈
    prevCircle.disableMassClear();
  },
  // 显示区域圆圈-移动端点击事件
  addCircle() {
    const self = this;

    const circleList = dbcircle.data.data;
    // 移动地图中心
    map.panTo(new BMap.Point(123.426531, 41.795455));
    // 设置地图等级
    map.setZoom(13);
    circleList.forEach((ele) => {
      var myCompOverlay = new ComplexCustomOverlayCircle(new BMap.Point(ele.Map_BD_Lng, ele.Map_BD_Lat), ele.name, ele);
      map.addOverlay(myCompOverlay);
      BMapLib.EventWrapper.addDomListener(myCompOverlay._div, "touchend", function () {
          myCompOverlay.click();
      });
      circleStorage.push(myCompOverlay);
    });

  },
  removeCircle() {
    circleStorage.forEach((ele) => {
      map.removeOverlay(ele);
    });
    circleStorage = [];
  },
  
};

// 右键菜单事件
var menu = new BMap.ContextMenu();
var txtMenuItem = [
  {
    text: '附近500米',
    callback: function (point) { handle.circle(point, 500) }
  },
  {
    text: '附近1公里',
    callback: function (point) { handle.circle(point, 1000) }
  },
  {
    text: '附近1.5公里',
    callback: function (point) { handle.circle(point, 1500) }
  },
  {
    text: '附近2公里',
    callback: function (point) { handle.circle(point, 2000) }
  },
];
for (var i = 0; i < txtMenuItem.length; i++) {
  menu.addItem(new BMap.MenuItem(txtMenuItem[i].text, txtMenuItem[i].callback, 100)); // 100为菜单宽度
}
map.addContextMenu(menu);






// 自定义覆盖物-多边形
function ComplexCustomOverlayView(map, params, polygonFn) {
  // 地图示例/参数/多边形区域方法
  this._map = map;
  this._params = params;
  this._polygonFn = polygonFn;
}
ComplexCustomOverlayView.prototype = new BMap.Overlay();
ComplexCustomOverlayView.prototype.initialize = function () {
  const div = (this._div = document.createElement("div"));
  div.style.position = "absolute";
  // div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
  div.style.backgroundColor = "#EE5D5B";
  div.style.border = "1px solid #EE5D5B";
  div.style.height = "24px";
  div.style.lineHeight = "24px";
  div.style.whiteSpace = "nowrap";
  div.style.fontSize = "12px";
  const span = (this._span = document.createElement("span"));
  span.style.color = "white";
  div.appendChild(span);
  span.innerHTML = this._params.name;
  const arrow = (this._arrow = document.createElement("div"));
  arrow.style.background =
    "url(https://g.517cdn.com/mis/misnet2014css/images/mapPoint.png) no-repeat";
  arrow.style.position = "absolute";
  arrow.style.width = "11px";
  arrow.style.height = "10px";
  arrow.style.top = "22px";
  arrow.style.left = "10px";
  arrow.style.overflow = "hidden";
  arrow.style.backgroundPosition = "0px 0px";
  div.appendChild(arrow);

  const self = this;
  div.onmouseover = function () {
    self._map.addOverlay(self._polygonFn);
  };
  div.onmouseout = function () {
    self._map.removeOverlay(self._polygonFn);
  };
  // 将div添加到覆盖物容器中
  this._map.getPanes().labelPane.appendChild(div);
  console.log(div);
  return div;
};
ComplexCustomOverlayView.prototype.draw = function () {
  const pixel = this._map.pointToOverlayPixel(
    new BMap.Point(this._params.lng, this._params.lat)
  );
  this._div.style.left = pixel.x - parseInt(this._arrow.style.left) + "px";
  this._div.style.top = pixel.y - 30 + "px";
};

// 移动端点击事件


// 自定义覆盖物-行政区
function ComplexCustomOverlayCircle(point, text, ele) {
  this._point = point;
  this._text = text;
  this._id = ele.id;
  this._lat = ele.Map_BD_Lat;
  this._lng = ele.Map_BD_Lng;
}
ComplexCustomOverlayCircle.prototype = new BMap.Overlay();
ComplexCustomOverlayCircle.prototype.initialize = function (map) {
  this._map = map;
  var div = this._div = document.createElement("div");
  div.style.position = "absolute";
  div.style.zIndex = BMap.Overlay.getZIndex(this._point.lat);
  div.style.backgroundColor = "#58C984";
  div.style.opacity = "0.8";
  div.style.height = "74px";
  div.style.lineHeight = "74px";
  div.style.width = "74px";
  div.style.borderRadius = "37px";
  div.style.fontSize = "14px";
  div.setAttribute('data-id', this._id);
  div.setAttribute('data-lat', this._lat);
  div.setAttribute('data-lng', this._lng);
  var span = this._span = document.createElement("span");
  span.style.display = "inline-block";
  span.style.width = "74px";
  span.style.height = "74px";
  span.style.lineHeight = "74px";;
  span.style.textAlign = "center";
  span.style.color = "white";
  div.appendChild(span);
  span.appendChild(document.createTextNode(this._text));
  map.getPanes().labelPane.appendChild(div);
  this._div = div;
  return div;
}

ComplexCustomOverlayCircle.prototype.draw = function () {
  var map = this._map;
  var pixel = map.pointToOverlayPixel(this._point);
  this._div.style.left = pixel.x - 37 + "px";
  this._div.style.top = pixel.y - 37 + "px";
}

// 自定义方法
ComplexCustomOverlayCircle.prototype.click = function () {
  var lat = this._lat;
  alert(lat);
}